import {createRouter, createWebHistory} from 'vue-router'
import {getToken} from "@/utils/auth";
import store from '@/store'
const routes = [
    {
        path: '/',
        name: 'home',
        component: () => import('@/views/home.vue')
    },
    {
        path: '/login',
        name: 'login',
        component: () => import('@/views/login')
    },
    {
        path: '/about',
        name: 'about',
        // route level code-splitting
        // this generates a separate chunk (about.[hash].js) for this route
        // which is lazy-loaded when the route is visited.
        component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
    }
]

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
})

router.beforeEach((to, from, next) => {
    if (getToken()) {//已登录
        if (to.name === 'login') next('/') // 如果访问的是登陆页面，直接跳转到主页
        else next() //想去哪里就去哪里
    } else if (to.name !== 'login')
        //没有登录
        next({name: 'login'}) //如果不是登陆页面，重定向到登陆页面
    else next() //如果是登陆页面，就直接放行
})
export default router
